<?php


namespace app;


use app\model\Category;
use app\model\NavCate;
use app\model\Route;
use app\model\Theme;
use app\model\Website;
use app\model\WebsiteLang;
use app\model\WebsiteServer;
use app\model\WebsiteSetting;
use app\service\ThemeService;
use think\facade\Db;

class WebsiteService
{
    /**
     * @throws exception\ModelEmptyException
     * @throws exception\ModelException
     */
    public function deleteSite($siteId, $sellerId): array
    {
        $themePath = CMS_ROOT . 'public' . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . 'website' . DIRECTORY_SEPARATOR . $siteId;
        $adminPath = CMS_ROOT . 'view' . DIRECTORY_SEPARATOR . 'website' . DIRECTORY_SEPARATOR . $siteId;
        Db::startTrans();
        try{
            $Website = new Website();
            $siteWhere  = ['id'=>$siteId,'seller_id'=>$sellerId];
            $where = ['seller_id'=>$sellerId,'website_id'=>$siteId];
            $website = $Website -> getWebsite($siteWhere)['data'];
            $category = new Category();
            $category -> delCustomData($where);
            // 站点主题相关数据
            $Theme = new Theme();
            $theme = $Theme -> getAllCustomDataModel($where,'id desc','*',['themeFile','bigField'])['data'];

            foreach($theme as $val){
                $val -> together(['themeFile','bigData']) -> delete();
            }
            // 站点基本配置
            $siteSetting = new WebsiteSetting();
            $siteSetting -> delCustomData($where);
            // 站点语言+服务器配置
            $siteLang = new WebsiteLang();
            $siteLang -> delCustomData($where);
            $siteServer = new WebsiteServer();
            $siteServer -> delCustomData($where);
            // 删除路由数据
            $route = new Route();
            $route -> delCustomData($where);
            // 删除网站
            $website -> delete();
            // 站点主题相关文件
            $themeService = new ThemeService();
            $themeService -> deleteFile($themePath);
            $themeService -> deleteFile($adminPath);
            // 站点路由美化文件
            $routePath = CMS_ROOT . 'route';
            $start = $siteId . '_';
            $routeFile = glob("$routePath/$start*.php");
            foreach ($routeFile as $file){
                @unlink($file);
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return dataReturn(-1,$e->getMessage());
        }

        return dataReturn(0,'删除成功');
    }
}